<template>
  <div class="app-container">
    <el-form :model="formData" ref="formDataRef" :rules="formDataRules" label-position="left">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="formData.deviceName" placeholder="设备名称" clearable style="width: 100%;"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <ActionButtons @reset="handleReset" @query="queryUserList">
            <el-button type="primary" size="small" @click="handleAddMenu">新增</el-button>
          </ActionButtons>
        </el-col>
      </el-row>
    </el-form>
    <BaseTable :table-columns="tableColumns" :table-data="tableData" :options="tableOptions" :total="pages.total"
      v-model:page-num="pages.pageNum" v-model:page-size="pages.pageSize" @turnOn="queryUserList">
      <template v-slot:imgUrl="{ row }">
        <el-image :preview-teleported="true" style="width:100px;height:100px" :src="row.imgUrl"
          :preview-src-list="[row.imgUrl]"></el-image>
      </template>
      <template v-slot:operation="{ row }">
        <el-button type="primary" text :icon="InfoFilled" @click="handleTableItemView(row)">查看</el-button>
        <el-button type="primary" text :icon="Edit" @click="handleTableItemEdit(row)">编辑</el-button>
        <el-button type="danger" text :icon="Delete" @click="handleTableItemDel(row)">删除</el-button>
      </template>
    </BaseTable>
    <Dialog ref="dialogRef" :title="dialogOptions.title" :width="dialogOptions.width" @close="handleDialogClose"
      @confirm="handleDialogConfirm">
      <template v-slot:content>
        <el-form :model="diaFormData" ref="diaFormRef" :rules="diaFormRules" label-position="left" label-width="100px">
          <el-form-item label="设备照片" prop="imgUrl">
            <ImageSelector type="img" v-model:imgUrl="diaFormData.imgUrl"></ImageSelector>
          </el-form-item>
          <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="diaFormData.deviceName" placeholder="请输入设备名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备描述" prop="deviceDesc">
            <el-input v-model="diaFormData.deviceDesc" placeholder="请输入设备描述" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备特点" prop="deviceCharact">
            <el-input v-model="diaFormData.deviceCharact" type="textarea" :autosize="{ minRows: 4, maxRows: 16 }"
              placeholder="请输入设备特点，使用英文','分隔" clearable></el-input>
          </el-form-item>
          <el-form-item label="展示排序" prop="order">
            <el-input v-model="diaFormData.order" type="number" :min="0" placeholder="请输入展示排序" clearable></el-input>
          </el-form-item>
          <!-- <el-form-item label="链接类型" prop="linkType">
            <el-input v-model="diaFormData.linkType" placeholder="请输入链接类型" clearable></el-input>
          </el-form-item> -->
          <el-form-item label="链接地址" prop="toLink">
            <!-- <el-input v-model="diaFormData.toLink" placeholder="请输入链接地址" clearable></el-input> -->
            <el-select v-model="diaFormData.toLink" placeholder="请选择链接地址">
              <el-option v-for="item in deviceJumpList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>
  </div>
</template>
<script lang='ts' setup>
import { ref, reactive, onMounted } from 'vue'
import FSMessage from '@/utils/message'
import type { FormInstance, FormRules } from 'element-plus'
import BaseTable from '@/components/BaseTable/index.vue'
import ActionButtons from '@/components/ActionButtons/index.vue'
import Dialog from '@/components/Dialog/index.vue'
import { IPaginationForm } from '@/types/http'
import { resetForm, validateForm } from '@/utils/tools'
import useHooksTable from './useHooksTable'
import useHooksDialog from './useHooksDialog'
import { create, deleteOne, update, findWidthCondition, findById } from '@/api/handpicDevice'
import { Delete, Edit, InfoFilled } from '@element-plus/icons-vue'
import ImageSelector from '@/components/ImageSelector/index.vue'
import { getAllProdCategoryList } from '@/api/content/category'
import { cloneDeep } from 'lodash-es'
/* ------------------------------ variable ------------------------------ */
const formData = ref({
  deviceName: ''
})
const dialogRef = ref()
const formDataRef = ref<FormInstance>() // 筛选条件表单实例
const diaFormRef = ref<FormInstance>() // 弹窗表单实例
const formDataRules = ref<FormRules>()
const pages = ref<IPaginationForm>({
  pageSize: 20,
  pageNum: 1,
  total: 0
})
const { tableColumns, tableData, tableOptions } = useHooksTable()
const { diaFormData, dialogOptions } = useHooksDialog()
const diaFormRules = reactive<FormRules>({
  deviceName: [
    { required: true, message: '设备名称必填', trigger: 'blur' }
  ],
  deviceDesc: [
    { required: true, message: '设备描述必填', trigger: 'blur' }
  ],
  deviceCharact: [
    { required: true, message: '设备特点必填', trigger: 'blur' }
  ],
  order: [
    { required: true, message: '展示排序必填', trigger: 'blur' }
  ],
  imgUrl: [
    { required: true, message: '设备照片必填', trigger: 'blur' }
  ],
  linkType: [
    { required: true, message: '链接类型必填', trigger: 'blur' }
  ],
  toLink: [
    { required: true, message: '链接地址必填', trigger: 'blur' }
  ]

})
const deviceJumpList = ref<any>([])
/* ------------------------------ function ------------------------------ */

const handleReset = () => {
  resetForm(formDataRef.value)
  queryUserList()
}

/**
 * @breif: 条件查询
 * @return {*}
 */
const queryUserList = async () => {
  try {
    const res = await findWidthCondition({ ...pages.value, ...formData.value })
    tableData.value = res.data.rows
    pages.value.total = res.data.total
  } catch (e) {
    console.log(e)
  }
}

/**
 * @breif: 点击新增弹窗
 * @return {*}
 */
const handleAddMenu = () => {
  dialogOptions.value.openType = 1
  resetForm(diaFormRef.value)
  dialogRef.value.visiableDialog()
}

/**
 * @breif: 弹窗关闭回调
 * @return {*}
 */
const handleDialogClose = () => {
}

/**
 * @breif: 弹窗中确认新增内容
 * @return {*}
 */
const handleDialogConfirm = async () => {
  try {
    await validateForm(diaFormRef.value)
    const diaFormDataShadow = cloneDeep(diaFormData.value)
    if (typeof diaFormDataShadow.deviceCharact === 'string') {
      diaFormDataShadow.deviceCharact = diaFormDataShadow.deviceCharact.split(',')
    }
    console.log(diaFormDataShadow, 'diaFormDataShadow')
    dialogOptions.value.openType === 1 ? await create(diaFormDataShadow) : await update(diaFormDataShadow)
    FSMessage.success('操作成功')
    queryUserList()
    dialogRef.value.hideBtnLoading()
    dialogRef.value.invisiableDialog()
  } catch (error) {
    dialogRef.value.hideBtnLoading()
    console.log(error)
  }
}

/**
 * @breif: 编辑
 * @param {*} row
 * @return {*}
 */
const handleTableItemEdit = (row) => {
  dialogOptions.value.openType = 2
  diaFormData.value = JSON.parse(JSON.stringify(row))
  dialogRef.value.visiableDialog()
}

/**
 * @breif: 查看详情
 * @param {*} _id
 * @return {*}
 */
const handleTableItemView = async ({ _id }) => {
  try {
    const res = await findById(_id)
    diaFormData.value = res.data
    dialogRef.value.visiableDialog()
  } catch (error) {
    console.log(error)
  }
}

/**
 * @breif: 删除
 * @param {*} row
 * @return {*}
 */
const handleTableItemDel = (row) => {
  FSMessage.confirm('删除后不可恢复，是否确认删除?', '提示').then(async () => {
    deleteOne(row._id)
    await queryUserList()
    FSMessage.success('删除成功')
    dialogRef.value.invisiableDialog()
  }).catch(() => {
    FSMessage.info('已取消')
  })
}

onMounted(() => {
  getAllProdCategoryList().then(res => {
    res.data.forEach(item => {
      deviceJumpList.value.push({
        label: item.label,
        value: `/product?cateId=${item.value}&type=level1`
      })
    })
  })
})
queryUserList()
</script>
<style scoped lang='less'></style>
